<template>
  <div class="announcements-container">
    <TopNavbar />
    <div class="content-wrapper">
      <div class="page-header">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>系统公告</el-breadcrumb-item>
        </el-breadcrumb>
        <h2 class="page-title">系统公告</h2>
      </div>

      <el-card class="announcement-card" shadow="hover">
        <div slot="header" class="card-header">
          <div class="header-left">
            <i class="el-icon-bell"></i>
            <span>系统公告</span>
          </div>
          <div class="header-right">
            <el-input
              placeholder="搜索公告..."
              v-model="searchKeyword"
              class="search-input"
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch"
              clearable
              @clear="resetSearch">
            </el-input>
            <el-select v-model="selectedType" placeholder="公告类型" class="filter-select" clearable @change="handleFilter">
              <el-option 
                v-for="item in typeOptions" 
                :key="item.value" 
                :label="item.label" 
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>
        
        <!-- 无数据状态 -->
        <el-empty 
          v-else-if="announcements.length === 0" 
          description="暂无公告信息" 
          :image-size="200">
        </el-empty>
        
        <!-- 公告列表 -->
        <div v-else class="announcement-list">
          <transition-group name="fade-list" tag="div">
            <div 
              v-for="item in announcements" 
              :key="item.id" 
              class="announcement-item"
              @click="viewDetail(item.id)">
              <div class="announcement-info">
                <div class="announcement-title">
                  <el-tag 
                    v-if="item.priority === 2" 
                    size="small" 
                    type="danger" 
                    effect="dark">紧急</el-tag>
                  <el-tag 
                    v-else-if="item.priority === 1" 
                    size="small"
                    type="warning" 
                    effect="plain">重要</el-tag>
                  <span class="title-text">{{ item.title }}</span>
                </div>
                <div class="announcement-meta">
                  <span><i class="el-icon-user"></i> {{ item.publisher_id }}</span>
                  <span><i class="el-icon-document"></i> {{ item.type }}</span>
                  <span><i class="el-icon-view"></i> {{ item.view_count }}</span>
                  <span><i class="el-icon-time"></i> {{ formatDate(item.created_at) }}</span>
                </div>
              </div>
              <div class="announcement-summary">{{ getContentSummary(item.content) }}</div>
              <div class="announcement-footer">
                <el-button type="text" @click.stop="viewDetail(item.id)">
                  查看详情 <i class="el-icon-right"></i>
                </el-button>
              </div>
            </div>
          </transition-group>
        </div>
        
        <!-- 分页器 -->
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.pageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </el-card>
    </div>

    <!-- 页脚 -->
    <FooterBar />
  </div>
</template>

<script>
import announcementApi from '@/api/announcement';
import TopNavbar from '@/views/front/components/TopNavbar.vue';
import FooterBar from '@/views/front/components/FooterBar.vue';
export default {
  name: 'Announcements',
  components: {
    TopNavbar,
    FooterBar
  },
  data() {
    return {
      // 加载状态
      loading: true,
      
      // 公告列表
      announcements: [],
      
      // 搜索关键词
      searchKeyword: '',
      
      // 选中的公告类型
      selectedType: '',
      
      // 分页信息
      pagination: {
        pageNum: 1,
        pageSize: 10
      },
      
      // 总记录数
      total: 0,
      
      // 公告类型选项
      typeOptions: [
        { value: '通知', label: '通知' },
        { value: '维护', label: '维护' },
        { value: '活动', label: '活动' },
        { value: '其他', label: '其他' }
      ]
    };
  },
  created() {
    // 获取公告列表
    this.fetchAnnouncements();
  },
  methods: {
    /**
     * 获取公告列表
     */
    fetchAnnouncements() {
      this.loading = true;
      
      // 构造查询参数
      const params = {
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        keyword: this.searchKeyword,
        type: this.selectedType,
        status: 1 // 只查询已发布的公告
      };
      
      // 调用接口获取数据
      announcementApi.getAnnouncements(params)
        .then(response => {
          if (response && response.data) {
            // 修改这里，使用正确的数据结构路径
            // 后端返回的数据结构是 {code, msg, data: {total, rows}}
            this.announcements = response.data.rows || [];
            this.total = response.data.total || 0;
            console.log('获取到的公告列表:', this.announcements);
            this.initializeAnnouncement();
          } else {
            this.announcements = [];
            this.total = 0;
            this.$message.error('获取公告列表失败');
          }
        })
        .catch(error => {
          console.error('获取公告列表出错', error);
          this.$message.error('获取公告列表出错');
          this.announcements = [];
          this.total = 0;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    /**
     * 处理搜索
     */
    handleSearch() {
      this.pagination.pageNum = 1;
      this.fetchAnnouncements();
    },
    
    /**
     * 重置搜索
     */
    resetSearch() {
      this.searchKeyword = '';
      this.pagination.pageNum = 1;
      this.fetchAnnouncements();
    },
    
    /**
     * 处理筛选
     */
    handleFilter() {
      this.pagination.pageNum = 1;
      this.fetchAnnouncements();
    },
    
    /**
     * 处理页码变化
     * @param {number} pageNum - 页码
     */
    handleCurrentChange(pageNum) {
      this.pagination.pageNum = pageNum;
      this.fetchAnnouncements();
    },
    
    /**
     * 处理每页条数变化
     * @param {number} pageSize - 每页条数
     */
    handleSizeChange(pageSize) {
      this.pagination.pageSize = pageSize;
      this.pagination.pageNum = 1;
      this.fetchAnnouncements();
    },
    
    /**
     * 查看公告详情
     * @param {number} id - 公告ID
     */
    viewDetail(id) {
      // 记录查看次数
      announcementApi.incrementViewCount(id).catch(() => {});
      
      // 跳转到详情页
      this.$router.push(`/announcements/detail/${id}`);
    },
    
    /**
     * 格式化日期
     * @param {string} dateStr - 日期字符串
     * @returns {string} - 格式化后的日期
     */
    formatDate(dateStr) {
      if (!dateStr) return '';
      
      try {
        // 处理多种可能的日期格式
        let date;
        if (typeof dateStr === 'string') {
          // 如果是普通的日期时间字符串格式(不含T)，先标准化为ISO格式
          if (dateStr.indexOf('T') === -1) {
            // 替换空格为T，确保格式正确
            dateStr = dateStr.replace(/\s+/g, 'T');
          }
          // 标准化日期格式
          date = new Date(dateStr);
        } else {
          date = new Date(dateStr);
        }
        
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
          console.warn('无效的日期格式:', dateStr);
          return dateStr; // 返回原始字符串
        }
        
        return date.toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        });
      } catch (error) {
        console.error('日期格式化错误:', error, dateStr);
        return dateStr; // 出错时返回原始字符串
      }
    },
    
    /**
     * 获取内容摘要
     * @param {string} content - 公告内容
     * @returns {string} - 内容摘要
     */
    getContentSummary(content) {
      if (!content) return '';
      // 去除换行符，截取100个字符
      return content.replace(/[\r\n]/g, ' ').substring(0, 100) + (content.length > 100 ? '...' : '');
    },
    
    /**
     * 确保数据中的属性存在，防止因属性缺失导致的错误
     */
    initializeAnnouncement() {
      // 确保公告列表中的每个对象都有必要的属性
      this.announcements = this.announcements.map(item => {
        return {
          id: item.id || 0,
          title: item.title || '',
          content: item.content || '',
          type: item.type || '其他',
          priority: item.priority || 0,
          publisher_id: item.publisherId || item.publisher_id || '系统',
          view_count: item.viewCount || item.view_count || 0,
          created_at: item.createdAt || item.created_at || item.createdTime || item.createTime || new Date().toISOString(),
          start_time: item.startTime || item.start_time || item.effectiveStartTime || null,
          end_time: item.endTime || item.end_time || item.effectiveEndTime || null
        };
      });
    }
  }
};
</script>

<style scoped>
.announcements-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.content-wrapper {
  flex: 1;
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.page-header {
  margin-bottom: 20px;
  background-color: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
}

.page-title {
  margin-top: 15px;
  font-size: 24px;
  color: #303133;
  font-weight: 600;
  position: relative;
  padding-left: 12px;
}

.page-title:before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 20px;
  width: 4px;
  background-color: #409EFF;
  border-radius: 2px;
}

.announcement-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
  animation: slideUp 0.5s ease-in-out;
}

@keyframes slideUp {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.header-left i {
  margin-right: 8px;
  font-size: 18px;
  color: #409EFF;
}

.header-right {
  display: flex;
  align-items: center;
}

.search-input {
  width: 220px;
  margin-right: 10px;
}

.filter-select {
  width: 120px;
}

.loading-container {
  padding: 20px 0;
}

.announcement-list {
  margin-top: 10px;
}

.announcement-item {
  padding: 15px;
  border-bottom: 1px solid #EBEEF5;
  cursor: pointer;
  transition: all 0.3s;
}

.announcement-item:hover {
  background-color: #F5F7FA;
}

.announcement-item:last-child {
  border-bottom: none;
}

.announcement-title {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.title-text {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-left: 5px;
}

.announcement-meta {
  display: flex;
  flex-wrap: wrap;
  font-size: 13px;
  color: #909399;
  margin-bottom: 10px;
}

.announcement-meta span {
  margin-right: 15px;
  display: flex;
  align-items: center;
}

.announcement-meta i {
  margin-right: 4px;
}

.announcement-summary {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  margin-bottom: 10px;
}

.announcement-footer {
  text-align: right;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

/* 列表动画 */
.fade-list-enter-active, .fade-list-leave-active {
  transition: all 0.5s;
}

.fade-list-enter, .fade-list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

.fade-list-move {
  transition: transform 0.5s;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-right {
    margin-top: 10px;
    width: 100%;
  }
  
  .search-input, .filter-select {
    margin-bottom: 10px;
  }
  
  .announcement-meta {
    flex-direction: column;
  }
  
  .announcement-meta span {
    margin-bottom: 5px;
  }
}
</style> 